package com.cai.kcsj.controller;

import com.cai.kcsj.entity.User;
import com.cai.kcsj.service.UserServer;
import com.cai.kcsj.utils.DateUtil;
import com.cai.kcsj.utils.Uploadpath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @version 1.0
 * @author：蔡松坡
 * @date：2021/1/4 19 : 12
 * @package：com.cai.kcsj.controller
 */
@Controller
@RequestMapping("/user")
public class UserContoller {
    @Autowired
    private UserServer userServer;

    @RequestMapping("/user")
    public String selectAllUser(Model model){
        List<User> users = userServer.selectAllUser();
        model.addAttribute("userList",users);
        return "usermanager";
    }

    @RequestMapping("/update")
    public String updateUser(User user, MultipartFile mfile){
        if(!mfile.isEmpty()){
            String originalFilename = mfile.getOriginalFilename();
            String extensionName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = new Random().nextInt(200) + extensionName;
            String uploadPath = Uploadpath.getUploadPath();
            System.out.println("uploadPath:: "+uploadPath);
            try {
                mfile.transferTo(new File(uploadPath, newFileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
            user.setImg(newFileName);
        }else{
            user.setImg(user.getImg());
        }

        userServer.updateUser(user);
        return "redirect:/user/user";
    }

    @RequestMapping("/toUpdateEdit/{id}")
    public String toUpdateEdit(Model model,@PathVariable("id") Integer id){
        User user = userServer.selectUserById(id);
        model.addAttribute("user",user);
        return "userEdit";
    }
}
